<template>
	<view>
		<!-- <u-navbar back-text=""
		 back-icon-size="36" 
		 height="50" 
		 back-icon-name="arrow-leftward" 
		 title-color="#000"
		 back-icon-color="#000"
		 title="设备信息">
		 </u-navbar> -->
		 <mine-head title="设备信息"></mine-head>
		 <view class="pic-box">
		 	<image src="@/static/img/mine/watch1.png" mode=""></image>
			<!-- <view class="name">
				{{data.name}}
			</view> -->
		 </view>
		 <view class="list">
			 <view class="item" @click="show = true">
			 	<view class="title">
			 		手表名称
			 	</view>
			 	<view class="info">
			 		{{name}}
			 	</view>
			 </view>
		 	<view class="item">
		 		<view class="title">
		 			固件版本
		 		</view>
				<view class="info">
					<u-loading mode="flower" size="28" v-if="versions == ''"></u-loading>
					{{versions}}
				</view>
		 	</view>
			<!-- <view class="item">
				<view class="title">
					蓝牙id
				</view>
				<view class="info">
					{{bluetooth}}
				</view>
			</view> -->
			<!-- <view class="item">
				<view class="title">
					批次号
				</view>
				<view class="info">
					<u-loading mode="flower" size="28" v-if="versions == ''"></u-loading>
					{{batch}}
				</view>
			</view> -->
			
		 </view>
		 <view class="btn">
		 	<u-button @click="submit" size="default" shape="circle" type="primary">解除绑定</u-button>
		 </view>
		 <u-popup v-model="show" :closeable="true" mode="center" border-radius="20" width="80%" height="400rpx">
		 	<view class="popCon">
		 		<view class="title">
		 			编辑手表名称
		 		</view>
		 		<view class="input-box">
		 			<u-input v-model="name" :border="true" placeholder="请输入" :height="60" :clearable="true" />
		 			<view class="btn2" @click="submit2">
		 				提交
		 			</view>
		 		</view>
		 		
		 	</view>
		 </u-popup>
		 <send-order ref="blue" @blueBack="blueBack"></send-order>
	</view>
</template>

<script>
	let timer = null;
	export default {
		data() {
			return {
				show:false,
				name:'',
				versions:'',
				bluetooth:'',
				batch:'',
				watchId:0,
				isJoin:false,
				deviceId: '',
				serviceId: '',
				writeId: '',
				notifyUuid: '',
				orderDataList:[
					{
						id:0,
						name:'错误码',
						len:1,
						value:'',
						data:'',
						dataLen:0
						
					},
					{
						id:1,
						name:'固件版本 v1.01',
						len:3,
						value:'',
						data:'',
						dataLen:0
					},
					{
						id:2,
						name:'固件ui版本 v1.01',
						len:3,
						value:'',
						data:'',
						dataLen:0
					},
					{
						id:3,
						name:'设备接收buf大小',
						len:2,
						value:'',
						data:'',
						dataLen:0
					},
					{
						id:4,
						name:'设备lcd宽，lcd高',
						len:4,
						value:'',
						data:'',
						dataLen:0
					},
					{
						id:5,
						name:'0：圆屏，1：方屏',
						len:1,
						value:'',
						data:'',
						dataLen:0
					},
					{
						id:6,
						name:'批次号（字符串X01G001）',
						len:16,
						value:'',
						data:'',
						dataLen:0
					},
					{
						id:7,
						name:'是否需要强制升级',
						len:1,
						value:'',
						data:'',
						dataLen:0
					},
					{
						id:8,
						name:'是否支持差分升级',
						len:1,
						value:'',
						data:'',
						dataLen:0
					},
					{
						id:9,
						name:'是否支持血糖功能',
						len:1,
						value:'',
						data:'',
						dataLen:0
					},
					{
						id:10,
						name:'蓝牙协议版本 ',
						len:3,
						value:'',
						data:'',
						dataLen:0
					},
					{
						id:11,
						name:'是否支持新睡眠算法',
						len:1,
						value:'',
						data:'',
						dataLen:0
					},
					
				],
				
			};
		},
		onLoad() {
			this.getWatch()
		},
		onShow() {
			
		},
		methods:{
			getWatch(){
				let that = this;
				uni.$_get({
					url: "get-watch",
					that: that,
					success(res) {
						let _data = res.data;
						if(res.code == 0){
							if(_data!=null){
								that.deviceId = _data.deviceId
								that.serviceId = _data.serviceId
								that.notifyUuid = _data.notifyUuid
								that.writeId = _data.writeId
								that.bluetooth = _data.deviceId
								that.name = _data.name
								that.watchId = _data.id
							}
						}
						
					},
					fail(err) {
						
					},
				});
			},
			blueBack(e,ids){
				this.isJoin = e
				if(e){
					setTimeout(()=>{
						this.writeFn('da070000')
					},1000)	
					// this.startNotice()
					// setTimeout(()=>{
						
					// },1000)
					
					
				}else{
					this.$refs.blue.getWatch()
				}
				
			},
			writeFn(orderVal) {
				var that = this
				let crc = uni.$_getCrc_16_ibm(orderVal)
				let val = orderVal + crc
				console.log(val, '发送的指令')
				let buff = uni.$_hexStringToArrayBuffer(val)
				uni.writeBLECharacteristicValue({
					// 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
					deviceId: that.deviceId,
					// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
					serviceId: that.serviceId,
					// 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
					characteristicId: that.writeId, //第二步写入的特征值
					// 这里的value是ArrayBuffer类型
					value: buff,
					success: function(res) {
						//此时设备已接收到你写入的数据
						console.log("写入成功", res)
						uni.onBLECharacteristicValueChange(result => {
							// console.log("监听低功耗蓝牙设备的特征值变化", result);
							if (result.value) {
								let resHex = uni.$_ab2hex(result.value)
								console.log('设备返回原始数据', resHex)
								clearInterval(timer)
								let dataObj = uni.$_parse_blue_response(resHex, 2)
								that.dataToArr(dataObj.Data,that.orderDataList)
								uni.stopPullDownRefresh();
								// if(that.dataObj.Head == 'da' && that.dataObj.Cmd == "87" ) {
									
								// 	console.log('转换数据', that.dataObj)
								// }
								
							}
						})
						
					},
					fail: function(err) {
						console.log(err)
						uni.hideLoading()
					},
					// complete: function() {
					// 	console.log("调用结束");
			
					// }
				})
			},
			startNotice() {
				var that = this;
				uni.notifyBLECharacteristicValueChange({
					state: true, // 启用 notify 功能
					// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接 
					deviceId: this.deviceId,
					// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
					serviceId: this.serviceId,
					// 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
					characteristicId: this.notifyUuid, //第一步 开启监听 notityid  第二步发送指令 write
					success(res) {
						//接收蓝牙返回消息
						// that.listenValueChange()
						console.log('接收蓝牙返回消息订阅成功')
						timer = setInterval(()=>{
							that.writeFn('da070000')
						},1000)	
					},
					fail(err) {
						console.log(err)
						uni.hideLoading()
						that.$refs.blue.getWatch()
					}
				})
			},
			dataToArr(dataList,orderDataList){
				orderDataList.forEach((item,index) =>{
					if(index == 0){
						item.dataLen = item.len
						item.value  = dataList.slice(0,item.dataLen)
					}else{
						item.dataLen = orderDataList[index-1].dataLen +orderDataList[index].len
						if(item.len>=2){
							let itemArr = dataList.slice(orderDataList[index-1].dataLen,item.dataLen)
							let str = itemArr.join('')
							item.value = str
							item.data = uni.$_hex2int(str)
						}else{
							let itemArr = dataList.slice(orderDataList[index-1].dataLen,item.dataLen)
							let str = itemArr.join('')
							item.value = str
							item.data = uni.$_hex2int(str)
							
						}
					}
				})
				// uni.showToast({
				// 	title:'获取成功！',
				// 	icon:'success'
				// })
				this.orderDataList = orderDataList
				console.log(this.orderDataList,'设备信息')
				this.versions = 'V' + this.addColonEveryTwoChars(orderDataList[1].value,'.')
				this.batch = orderDataList[6].value
				uni.hideLoading()
			},
			addColonEveryTwoChars(str,symbol) {
			  let result = '';
			  for (let i = 0; i < str.length; i += 2) {
			    result += str.substr(i, 2) + symbol;
			  }
			  // 如果最后一位是单个字符，则直接添加
			  if (str.length % 2 === 1) {
			    result += str.charAt(str.length - 1);
			  }
			  // 移除最后一个冒号
			  result = result.substr(0, result.length - 1);
			  return result;
			},
			addData(){
				let that = this
				let p = {
					name:this.name,
					id:this.watchId,
					deviceId:this.deviceId,//设备 id
					serviceId:this.serviceId,//蓝牙特征值对应服务的 uuid
					notifyUuid:this.notifyUuid,//开启蓝牙消息监听 uuid
					writeId:this.writeId,//蓝牙写入指令 uuid
				}
				uni.$_post({
					url: "watchLinkRecord",
					that: that,
					params: p,
					success(res) {
						console.log(res)
						if(res.code == 0){
							setTimeout(()=>{
								uni.navigateBack()
							},500)
						}else{
							uni.showToast({
								title: res.msg,
								duration: 2000,
								icon:'error'
							});
						}
					},
					fail(err) {
						uni.showToast({
							title: err.msg,
							duration: 1000,
							icon:'error'
						});	
					},
				});
			},
			submit2(){
				this.addData()
			},
			submit(){
				let that = this
				const systemInfo = uni.getSystemInfoSync();
				if (systemInfo.platform === 'android') {
				    console.log('当前系统是安卓');
				    
				} else if (systemInfo.platform === 'ios') {
				    console.log('当前系统是iOS');
					
					
					
				} else {
				    console.log('平台未知：', systemInfo.platform);
				}
				uni.$_publicModal(
				  "彻底断开设备需到手机蓝牙设置忽略此设备。",
				  function () {
				    setTimeout(() =>{
				    	that.name = ''
				    	that.deviceId = ''//设备 id
				    	that.serviceId = ''//蓝牙特征值对应服务的 uuid
				    	that.notifyUuid = ''//开启蓝牙消息监听 uuid
				    	that.writeId = ''//蓝牙写入指令 uuid
				    	that.addData()
				    },1000)
				  }
				);
				// console.log(this.deviceId)
				// uni.openAppAuthorizeSetting({
				// 	success: function () {
				// 		console.log('打开系统设置页面成功');
				// 	},
				// 	fail: function () {
				// 		console.log('打开系统设置页面失败');
				// 	}
				// });
				
				
			}
		},
		onPullDownRefresh() {
			let that = this
			this.writeFn('da070000')
			this.getWatch()
		}
	}
</script>

<style lang="scss" scoped>
/deep/.u-title{
	font-size: 34rpx !important;
	font-family: $uni-font-family-Bold;
}
.popCon{
	position: relative;
	.title{
		width: 100%;
		height: 90rpx;
		line-height: 90rpx;
		text-align: center;
		font-size: 30rpx;
		color: #333;
		background-color: #f4f4f4;
		font-family: $uni-font-family-Heavy;
	}
	.input-box{
		padding: 40rpx 40rpx;
	}
	.btn2{
		margin-top: 70rpx;
		width: 100%;
		height: 70rpx;
		line-height: 70rpx;
		text-align: center;
		font-size: 30rpx;
		color: #fff;
		font-family: $uni-font-family-Heavy;
		border-radius: 35rpx;
		background-color: #6387FF;
	}
}
.pic-box{
	padding: 80rpx 30rpx 50rpx;
	border-bottom: 1rpx solid #eee;
	margin-bottom: 30rpx;
	image{
		width: 400rpx;
		height: 434rpx;
		margin: 0 auto 50rpx;
		display: block;
	}
	.name{
		text-align: center;
		font-size: 32rpx;
		color: #2F2C44;
		font-family: $uni-font-family-Heavy;
	}
}
.list{
	padding: 0 50rpx;
	.item{
		height: 100rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 10rpx;
		.title{
			font-size: 32rpx;
			color: #000;
		}
		.info{
			font-size: 24rpx;
			color: #aaa;
		}
	}
}
.btn{
	padding: 30rpx 50rpx;
	/deep/.u-btn--primary{
		background-color: #6387FF;
		border-color: #6387FF;
	}
}
</style>
